package com.connector.server.handler;

import org.slf4j.LoggerFactory;
import com.connector.base.message.model.BaseMessage;
import com.connector.base.connection.SessionContext;
import com.connector.server.util.PushMsgUtil;
import com.connector.base.utils.ErrorCode;
import com.connector.base.message.model.HandshakeMessage;
import com.google.common.base.Strings;
import com.connector.base.connection.Connection;
import com.connector.base.protocol.Packet;
import org.slf4j.Logger;
import com.connector.base.message.model.HandshakeCheckMessage;
import com.connector.base.handler.BaseMessageHandler;

public class HandShakeCheckHandler extends BaseMessageHandler<HandshakeCheckMessage>
{
    private static final Logger log;
    
    public HandshakeCheckMessage decode(final Packet packet, final Connection connection) {
        return new HandshakeCheckMessage(packet, connection);
    }
    
    public void handle(final HandshakeCheckMessage message) {
        final String msg = message.getMsg();
        if (Strings.isNullOrEmpty(msg)) {
            HandshakeMessage.buildErrorResponse(message.getConnection()).setErrorCode(ErrorCode.INVALID_DEVICE).buildResult("Param invalid", "发送消息不能为空！").close();
            HandShakeCheckHandler.log.error("handshake check error, message={}, conn={}", (Object)message, (Object)message.getConnection());
            return;
        }
        final SessionContext context = message.getConnection().getSessionContext();
        final String appId = context.getAppid();
        if (Strings.isNullOrEmpty(appId)) {
            HandshakeMessage.buildErrorResponse(message.getConnection()).setErrorCode(ErrorCode.INVALID_DEVICE).buildResult("Param invalid", "发送消息不能为空！").close();
            HandShakeCheckHandler.log.error("handshake check error, message={}, conn={}", (Object)message, (Object)message.getConnection());
            return;
        }
        try {
            context.setTime2(System.currentTimeMillis());
            PushMsgUtil.pushHandshakeCheckAppMsg(message.getConnection(), msg);
        }
        catch (Throwable e) {
            HandshakeMessage.buildErrorResponse(message.getConnection()).setErrorCode(ErrorCode.UNKNOWN).buildResult(e.getMessage(), "证书检测失败！").close();
            HandShakeCheckHandler.log.error("chat failure!", e);
        }
    }
    
    static {
        log = LoggerFactory.getLogger((Class)HandShakeCheckHandler.class);
    }
}
